const express = require('express');
const bodyParser = require('body-parser');
const multipart = require('connect-multiparty');
const cors = require('cors')

const app = express();
const fs = require("fs");

/* 配置跨域 */
app.use(cors())
/* app 配置 */
app.use(require('cookie-parser')());
// 解析 application/json
app.use(bodyParser.json());
// 解析 application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));
// app.use('/public',express.static(path.join(__dirname, 'public')));
app.use(multipart());

// 设置 view 内容部分
// app.set('views', path.join(__dirname, 'views'));

// 定义 html 模板引擎
function rawHtmlViewEngine(filename, options, callback) {
    fs.readFile(filename, 'utf8', function (err, str) {
        callback(err, str);
    });
}
app.engine('html', rawHtmlViewEngine);
app.set('view engine', 'html');
//注册跨域中间件
// app.use(require('cors')({
//     origin: 'http://localhost:8080',
//     //这一项是为了跨域专门设置的
//     credentials: true,
//     maxAge: '1728000'
// }));
app.all('/*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin",  req.headers.origin);
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Allow-Credentials","true");
    res.header("X-Powered-By",' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

module.exports = app;